#include <ESP8266WiFi.h>

#define STASSID "ssid"
#define STAPSK  "password"

const    char* remote_ip   = "192.168.4.1";
unsigned int   remote_port = 12580;      // local port to listen on

WiFiClient client;

void setup()
{ 
  Serial.begin(115200);
  Serial.println("STA MODE");
  WiFi.mode(WIFI_STA);
  WiFi.begin(STASSID, STAPSK);
  Serial.println("WiFi connecting...");
  while (WiFi.status() != WL_CONNECTED) {
    delay(100);
  }
  Serial.println("WiFi connected!!!");
  
  Serial.println("tcp server connecting...");
  while(client.status() == CLOSED){
    client.connect(remote_ip, remote_port);
    delay(100);
  }
  client.setNoDelay(true); //无发送延时
  Serial.println("tcp server connected!");
  
}

void loop()
{
  if(client.status() == CLOSED){
	//意外断开重连
    Serial.println("tcp server Connecting...");
    while(client.status() == CLOSED){
      client.connect(remote_ip, remote_port);
      delay(100);
    }
    Serial.println("tcp server Connected!");
  }
  if(client.available()){
      //从客户端获取数据
      while(client.available()){
        //将数据转发到URAT端口
        Serial.write(client.read());
      }       
  }
  if(Serial.available()){
    size_t len = Serial.available();
    uint8_t sbuf[len];
    Serial.readBytes(sbuf, len);
    //将UART端口数据转发到已连接的客户端
    client.write(sbuf, len);
  }
}



  
